const fs = require('fs');

const k = LB.HELPER.MD5("#$&qbJSv685vgSAE54745672941VW$hjhhL%^1223bA*54*3").substr(0,16)
const iv = LB.HELPER.MD5("1145141919810").substr(16,32)

var apd = {}

LB.HELPER.APD = {};

try{        //玩家数据初始化
    if(fs.statSync('./config/players.apd','r')){
        LB.log.ok("玩家数据加载成功！");
    }
}catch(err){
    LB.log.busy("玩家数据不存在，正在初始化...")
    fs.writeFileSync('./config/players.apd', LB.HELPER.AES.encrypt(k,iv,"{}"));
    LB.log.ok("玩家数据初始化成功！");
}

apd = JSON.parse(LB.HELPER.AES.decrypt(k,iv,fs.readFileSync('./config/players.apd','utf8')));

LB.HELPER.APD.XboxID_existed = function(xid){      //检查xboxid是否已被绑定，返回true/false
    return Object.keys(apd).some((a)=> a===xid)
}

LB.HELPER.APD.getPlayersInfo = function(qq){   //获取玩家数据，获取到则返回一个对象，获取不到返回undefined
    let xid = LB.HELPER.APD.getXboxID(qq)
    if (xid != false){
        return apd[xid]
    }
    return false
}

LB.HELPER.APD.getQQ = function(xid){            //获取xboxid对应的qq号码，获取到则返回qq号码，获取不到则返回undefined
    if(LB.HELPER.APD.XboxID_existed(xid)){
        return apd[xid].qqid
    }
}

LB.HELPER.APD.getPermission = function(qq){     //获取xboxid的权限值，获取到则返回0/1；获取不到返回undefined
    if(LB.HELPER.APD.getPlayersInfo(qq)){
        return LB.HELPER.APD.getPlayersInfo(qq).permission
    }
}

LB.HELPER.APD.getBindStatus = function(qq){   //检查玩家是否已加过白名单，获取到则返回true/false，获取不到返回undefined
    if(LB.HELPER.APD.getPlayersInfo(qq)){
        return LB.HELPER.APD.getPlayersInfo(qq).enable
    }
}

LB.HELPER.APD.getXboxID = function(qq){         //获取qq对应的xboxid，获取到则返回xboxid，获取不到则返回undefined
    for(g in Object.values(apd)){
        if(Object.values(apd)[g].qqid == qq){
            return Object.keys(apd)[g]
        }
    }
}

LB.HELPER.APD.bindXboxID = function(qq,xid){    //绑定xboxid
    let adminGroup = LB.CONFIG.global.administrators

    if(adminGroup.some((val) => val===qq)){
        apd[xid] = {qqid:qq,permission:1,enable:false}
    }
    else{
        apd[xid] = {qqid:qq,permission:0,enable:false}
    }
    LB.HELPER.APD.write()
}

LB.HELPER.APD.addWhitelist = function(qq){    //加白名单
    if(LB.HELPER.APD.getXboxID(qq) != undefined){
        let xid = LB.HELPER.APD.getXboxID(qq)
        apd[xid].enable = true
        LB.HELPER.APD.write()
    }
}

LB.HELPER.APD.unbindXboxID = function(qq){    //解绑xboxid
    if(LB.HELPER.APD.getXboxID(qq) != undefined){
        let xid = LB.HELPER.APD.getXboxID(qq)
        delete apd[xid];
        LB.HELPER.APD.write()
    }
}

LB.HELPER.APD.write = function(){           //将数据加密写入文件
    fs.writeFileSync('./config/players.apd',LB.HELPER.AES.encrypt(k,iv,JSON.stringify(apd)));
}